package p16.code;

import java.math.BigInteger;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class BrokenPrimeProducer extends Thread{

    private final BlockingQueue<BigInteger> queue;//声明阻塞队列
    private volatile boolean cancelled = false;//声明请求取消标志

    public BrokenPrimeProducer(BlockingQueue<BigInteger> queue){
        this.queue = queue;
    }

    public void run(){
        try{
            BigInteger p = BigInteger.ONE;
            while(!cancelled)
                queue.put(p = p.nextProbablePrime());//将产生的素数放入阻塞队列中
        }
        catch(InterruptedException ignored){

        }
    }

    public void cancel(){ cancelled = true;}


}

class Test{

    public static void main(String[] args) {
        BlockingQueue<BigInteger> primes = new LinkedBlockingQueue<BigInteger>(2);
        BrokenPrimeProducer producer = new BrokenPrimeProducer(primes);
        producer.start();
        try{
            while(true) {
                System.out.println(primes.take());
                Thread.sleep(100);
                break;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            producer.cancel();
        }
    }

}
